<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" v-show="showSearch" label-width="100px">
      <el-row>
        <el-col :span="6">
          <el-form-item label="客户姓名" prop="custName">
            <el-input v-model="queryParams.custName" placeholder="请输入客户姓名" clearable @keyup.enter.native="handleQuery"
              style="width:100%" />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="queryParams.mobile" placeholder="请输入手机号" clearable @keyup.enter.native="handleQuery"
              style="width:100%" />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="合同编号" prop="contractNo">
            <el-input v-model="queryParams.contractNo" placeholder="请输入合同编号" clearable @keyup.enter.native="handleQuery"
              style="width:100%" />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="签约时间" prop="signTime">
            <el-date-picker v-model="signTime" type="daterange" :picker-options="pickerOptions" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" format="yyyy-MM-dd"
              align="right" style="width: 100%;">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>

        <el-col :span="6">
          <el-form-item label="顾问" prop="empId">
            <el-select v-model="queryParams.empId" placeholder="顾问" clearable filterable style="width:100%"
              :disabled="empDisable">
              <el-option v-for="user in sysUsersList" :key="user.userId" :label="user.nickName" :value="user.userId" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="部门归属" prop="orgId">
            <treeselect v-model="queryParams.orgId" :options="deptOptions" :show-count="true" placeholder="请选择部门归属"
              :default-expand-level="4" style="width:100%" :disabled="orgDisable" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['custinfo:contractInfo:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['custinfo:contractInfo:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['custinfo:contractInfo:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="contractInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" align="center" min-width="3%">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="部门归属" align="center" prop="orgId" min-width="3%">
        <template slot-scope="scope">
          {{ getDeptByOrgId(scope.row.orgId) }}
        </template>
      </el-table-column>
      <el-table-column label="顾问" align="center" prop="empId" min-width="3%">
        <template slot-scope="scope">
          {{ getNameByEmpId(scope.row.empId) }}
        </template>
      </el-table-column>
      <el-table-column label="客户姓名" align="center" prop="custName" min-width="3%" />
      <el-table-column label="手机号" align="center" prop="mobile" min-width="3%" />
      <el-table-column label="合同编号" align="center" prop="contractNo" min-width="3%" />
      <el-table-column label="合同照片" align="center" prop="contractImage" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.contractImage" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="签约时间" align="center" prop="signTime" min-width="3%" />
      <el-table-column label="费率%" align="center" prop="loanRate" min-width="3%" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="3%">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['custinfo:contractInfo:edit']">修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改合同管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户姓名" prop="custName">
              <el-input v-model="form.custName" placeholder="请输入客户姓名" />
            </el-form-item>

          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="form.mobile" placeholder="请输入手机号" :rules="[{ validator: phoneNumberValidator }]" />
            </el-form-item>

          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">

            <el-form-item label="合同编号" prop="contractNo">
              <el-input v-model="form.contractNo" placeholder="请输入合同编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="签约时间" prop="signTime">
              <el-date-picker v-model="form.signTime" type="date" placeholder="选择日期" value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>

          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="合同照片" prop="contractImage">
              <image-upload v-model="form.contractImage" />
            </el-form-item>

          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="顾问" prop="empId">
              <el-select v-model="form.empId" placeholder="顾问" clearable filterable style="width:100%"
                :disabled="empDisable">
                <el-option v-for="user in sysUsersList" :key="user.userId" :label="user.nickName"
                  :value="user.userId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门归属" prop="orgId" :disabled="orgDisable">
              <treeselect v-model="form.orgId" :options="deptOptions" :show-count="true" placeholder="请选择部门归属"
                :default-expand-level="4" style="width:100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="联系地址" prop="address">
              <el-input type="textarea" :rows="2" v-model="form.address" placeholder="请输入联系地址" />
            </el-form-item>

          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="费率%" prop="loanRate">
              <el-input v-model="form.loanRate" placeholder="请输入费率%" />
            </el-form-item>

          </el-col>
          <el-col :span="12">

          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listContractInfo, getContractInfo, delContractInfo, addContractInfo, updateContractInfo } from "@/api/custinfo/contractInfo";
import {
  getAllDeptandUsers
} from "@/api/crmsys/custinfo/custinfo";


import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import Treeselect from "@riophae/vue-treeselect";
import { childrenAlldeptTree } from "@/api/system/user";


export default {
  name: "ContractInfo",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      signTime: null,
      orgDisable: false,
      empDisable: false,
      // 总条数
      total: 0,
      // 合同管理表格数据
      contractInfoList: [],
      sysUsersList: [],
      // 弹出层标题
      title: "",
      isEmp: 0,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        custName: null,
        mobile: null,
        contractNo: null,
        contractImage: null,
        signTime: null,
        loanRate: null,
        address: null,
        empId: null,
        orgId: null,
        empName: null,
        orgName: null,
      },
      // 表单参数
      form: {},
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      pickerOptions2: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      // 部门归属树选项
      deptOptions: [],
      // 表单校验
      rules: {
        custName: [
          { required: true, message: "客户姓名不能为空", trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        contractImage: [
          { required: true, message: "合同照片不能为空", trigger: "blur" }
        ],
        signTime: [
          { required: true, message: "签约时间不能为空", trigger: "blur" }
        ],
        loanRate: [
          { required: true, message: "费率%不能为空", trigger: "blur" },
          { pattern: /^[0-9]+(\.[0-9]{1,6})?$/, message: '费率%格式不正确', trigger: ['change', 'blur'] }
        ],
        empId: [
          { required: true, message: "顾问id不能为空", trigger: "blur" }
        ],
        orgId: [
          { required: true, message: "部门归属id不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询合同管理列表 */
    getList() {
      this.loading = true;
      listContractInfo(this.queryParams).then(response => {
        this.contractInfoList = response.data.list.rows;
        this.total = response.data.list.total;
        this.loading = false;
        this.isEmp = response.data.isEmp;

        //先判断是否是员工，再加载层级
        this.getDeptTree();
        this.getDeptAndUsers();
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        custName: null,
        mobile: null,
        contractNo: null,
        contractImage: null,
        signTime: null,
        loanRate: null,
        address: null,
        empId: null,
        orgId: null,
        empName: null,
        orgName: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加合同管理";
      if (this.isEmp == 1) {
        this.form.empId = this.$store.state.user.id;
        this.form.orgId = this.$store.state.user.deptid;
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      if (this.isEmp == 1) {
        this.form.empId = this.$store.state.user.id;
        this.form.orgId = this.$store.state.user.deptid;
      }
      const id = row.id || this.ids
      getContractInfo(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改合同管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateContractInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addContractInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除合同管理编号为"' + ids + '"的数据项？').then(function () {
        return delContractInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('custinfo/contractInfo/export', {
        ...this.queryParams
      }, `contractInfo_${new Date().getTime()}.xlsx`)
    },
    /** 查询部门归属下拉树结构 */
    getDeptTree() {
      var dept = { deptId: this.$store.state.user.deptid }
      childrenAlldeptTree(dept).then(response => {
        this.deptOptions = response.data;
        if (this.isEmp == 1) {
          this.orgDisable = true;
          this.queryParams.orgId = this.$store.state.user.deptid;
          this.form.orgId = this.$store.state.user.deptid;
        }

      });
    },
    /** 获取部门归属和人员信息 */
    getDeptAndUsers() {
      getAllDeptandUsers().then((response) => {
        this.sysUsersList = response.data.sysUsersList;
        if (this.isEmp == 1) {
          //如果是员工，则默认选中自己
          this.empDisable = true;
          this.form.empId = this.$store.state.user.id;
          this.queryParams.empId = this.$store.state.user.id;
        }
      });
    }, phoneNumberValidator(rule, value, callback) {
      if (value === '') {
        callback(); // 如果没有输入值，直接通过校验
      } else {
        const regExp = /^((\+86)|(86))?\d{11}$/; // 手机号正则表达式
        if (!regExp.test(value)) {
          callback('请输入正确的手机号'); // 若不符合手机号格式，调用callback传递错误消息
        } else {
          callback(); // 符合手机号格式，通过校验
        }
      }
    },
  }
};
</script>
